import os
import sys
import subprocess

def convert_mp4_to_aac(directory):
    for filename in os.listdir(directory):
        if filename.endswith('.mp4'):
            mp4_file = os.path.join(directory, filename)
            aac_file = os.path.join(directory, filename[:-4] + '.aac')
            
            # Try to copy audio stream without re-encoding
            result = subprocess.run(
                ['ffmpeg', '-i', mp4_file, '-vn', '-c:a', 'copy', '-f', 'adts', aac_file],
                stderr=subprocess.PIPE,
                stdout=subprocess.PIPE
            )
            
            if result.returncode == 0:
                print(f"Copied audio from {mp4_file} to {aac_file} without re-encoding")
            else:
                # If copy fails, fallback to encoding
                subprocess.run(
                    ['ffmpeg', '-i', mp4_file, '-vn', '-c:a', 'aac', '-b:a', '192k', aac_file]
                )
                print(f"Converted {mp4_file} to {aac_file} with encoding")

def main():
    if len(sys.argv) != 2:
        print("Usage: python script.py <directory>")
        sys.exit(1)
    
    directory = sys.argv[1]
    
    if not os.path.isdir(directory):
        print(f"Error: {directory} is not a valid directory")
        sys.exit(1)
    
    print("Converting MP4 files to AAC...")
    convert_mp4_to_aac(directory)
    print("Conversion completed.")

if __name__ == "__main__":
    main()
